﻿//统一文件为utf-8编码编译
#pragma execution_character_set("utf-8")
///////////////////////////////////////////////////////////////////////////
// 文件名:     widget.cpp
// 描述:
// 作者:      颜磊
// 创建工程：   SpaceClear
// 创建时间:   2024-07-24 15:30
///////////////////////////////////////////////////////////////////////////
#include "widget.h"
#include "delegatecenter.h"
#include "ui_widget.h"

#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QMenu>
#include <QSqlError>
#include <QSqlQuery>

#define _ZH_(x) QString(x)

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QFile file(QCoreApplication::applicationDirPath() + "/StyleSheet/BlackAndBlue.qss");
    if (file.open(QFile::ReadOnly))
    {
        setStyleSheet(file.readAll());
        file.close();
    }

    model = new QSqlTableModel(this, clearPathDB.getDataBase());
    model->setTable("ClearPath_table");
    ui->tableView->setModel(model);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); //单行选中
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);  //设置单元格不可编辑

    serverName = "SpaceClearService";
    serverDescription = "";
    serverPath = QCoreApplication::applicationDirPath() + "/SpaceClearService.exe";

    connect(&m_timer, &QTimer::timeout, this, &Widget::getServerState);
    m_timer.start(1000);

    model->setHeaderData(0, Qt::Horizontal, "id");
    model->setHeaderData(1, Qt::Horizontal, QString("路径"));
    model->setHeaderData(2, Qt::Horizontal, QString("过滤文件类型"));
    model->setHeaderData(3, Qt::Horizontal, QString("递归子文件夹"));
    model->setHeaderData(4, Qt::Horizontal, QString("数据量使能"));
    model->setHeaderData(5, Qt::Horizontal, QString("数据量"));
    model->setHeaderData(6, Qt::Horizontal, QString("数据量单位"));
    model->setHeaderData(7, Qt::Horizontal, QString("时差使能"));
    model->setHeaderData(8, Qt::Horizontal, QString("时差（秒级）"));
    model->setHeaderData(9, Qt::Horizontal, QString("时间选项"));
    model->setHeaderData(10, Qt::Horizontal, QString("使能"));

    ui->tableView->setColumnHidden(0, true);

    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //==========================枚举值代理
    QStringList enumList1{_ZH_("创建时间"), _ZH_("修改时间")};
    QStringList enumList2{_ZH_("关闭"), _ZH_("开启")};
    QStringList enumList3{_ZH_("MB"), _ZH_("GB"), _ZH_("TB")};

    EnumDelegate *enumDelegate1 = new EnumDelegate(enumList1, this);
    EnumDelegate *enumDelegate2 = new EnumDelegate(enumList2, this);
    EnumDelegate *enumDelegate3 = new EnumDelegate(enumList3, this);

    ui->tableView->setItemDelegateForColumn(9, enumDelegate1);
    ui->tableView->setItemDelegateForColumn(3, enumDelegate2);
    ui->tableView->setItemDelegateForColumn(4, enumDelegate2);
    ui->tableView->setItemDelegateForColumn(7, enumDelegate2);
    ui->tableView->setItemDelegateForColumn(6, enumDelegate3);
    ui->tableView->setItemDelegateForColumn(10, enumDelegate2);

    model->select();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::getServerState()
{
    serverState = deviceOperator.getServiceState(serverName.toStdString().c_str());
    ui->serviceAddDelBtn->setText(serverState == -1 ? QString("安装") : QString("卸载"));
    ui->serviceStartStopBtn->setText(serverState == SERVICE_RUNNING ? QString("停止") : QString("启动"));
    ui->serviceRestartBtn->setEnabled(serverState == SERVICE_RUNNING);
    ui->serviceStartStopBtn->setEnabled(serverState != -1);
    switch (serverState)
    {
    case -1:
        ui->serviceState->setText(QString("服务未安装！"));
        break;
    case SERVICE_RUNNING:
        ui->serviceState->setText(QString("服务已启动！"));
        break;
    case SERVICE_STOPPED:
        ui->serviceState->setText(QString("服务已停止！"));
        break;
    }
}

void Widget::addPath()
{
    savePathDialog = new SavePathDialog(0, nullptr, this);
    connect(savePathDialog, &SavePathDialog::signal_saveClearPath, this, &Widget::slot_saveClearPath);
    savePathDialog->exec();
}

void Widget::upPath()
{
    QModelIndex index = ui->tableView->selectionModel()->currentIndex();
    int iSel = index.row();

    ClearPath clearPath;
    clearPath.id = ui->tableView->model()->index(iSel, 0).data().toInt();
    clearPath.setPath(ui->tableView->model()->index(iSel, 1).data().toString().toStdString());
    clearPath.setFilterSuffix(ui->tableView->model()->index(iSel, 2).data().toString().toStdString());
    clearPath.cascade = ui->tableView->model()->index(iSel, 3).data().toBool();
    clearPath.data_number_enable = ui->tableView->model()->index(iSel, 4).data().toBool();
    clearPath.data_number = ui->tableView->model()->index(iSel, 5).data().toInt();
    clearPath.unit_option = ui->tableView->model()->index(iSel, 6).data().toInt();
    clearPath.time_enable = ui->tableView->model()->index(iSel, 7).data().toBool();
    clearPath.elapsed = ui->tableView->model()->index(iSel, 8).data().toInt();
    clearPath.time_option = ui->tableView->model()->index(iSel, 9).data().toInt();
    clearPath.enable = ui->tableView->model()->index(iSel, 10).data().toBool();
    savePathDialog = new SavePathDialog(1, &clearPath, this);
    connect(savePathDialog, &SavePathDialog::signal_saveClearPath, this, &Widget::slot_saveClearPath);
    savePathDialog->exec();
}

void Widget::delPath()
{
    QModelIndex index = ui->tableView->selectionModel()->currentIndex();
    int iSel = index.row();
    model->removeRow(iSel);
    model->submit();
    model->select();
}

void Widget::slot_saveClearPath(int saveType, ClearPath clearPath)
{
    qDebug() << "save";
    if (saveType == 0)
    {
        clearPathDB.addClearPath(clearPath);
    }
    else if (saveType == 1)
    {
        clearPathDB.upClearPath(clearPath);
    }
    model->select();
}

void Widget::on_serviceAddDelBtn_clicked()
{
    if (serverState == -1)
    {
        if (serverDescription.isEmpty())
            serverDescription = serverName;
        if (!serverName.isEmpty() && !serverPath.isEmpty())
            deviceOperator.InstallServiceInterface(serverName.toStdString().c_str(), serverDescription.toStdWString().c_str(), serverPath.toStdString().c_str());
        else
            ui->serviceState->setText(QString("服务名称和服务路径异常（路径错误）！"));
    }
    else
    {
        deviceOperator.UninstallServiceInterface(serverName.toStdString().c_str());
    }
}

void Widget::on_serviceStartStopBtn_clicked()
{
    if (serverState == SERVICE_STOPPED)
    {
        deviceOperator.StartServiceInterface(serverName.toStdString().c_str());
    }
    else if (serverState == SERVICE_RUNNING)
    {
        deviceOperator.StopServiceInterface(serverName.toStdString().c_str());
    }
}

void Widget::on_serviceRestartBtn_clicked()
{
    deviceOperator.StopServiceInterface(serverName.toStdString().c_str());
    deviceOperator.StartServiceInterface(serverName.toStdString().c_str());
}

void Widget::on_tableView_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu;
    QModelIndex index = ui->tableView->selectionModel()->currentIndex();
    int iSel = index.row();
    menu.addAction(QString("添加"), this, &Widget::addPath);
    if (iSel > -1)
    {
        menu.addAction(QString("修改"), this, &Widget::upPath);
        menu.addAction(QString("删除"), this, &Widget::delPath);
    }
    menu.exec(QCursor::pos());
}
